import { getRoles, getUserInfo } from "@/api/profile";

const state = {
  info: {},
  roles: [],
  currentRole: {},
  status: false
};

// actions
const actions = {
  // 获取用户信息
  async initUser({ dispatch }) {
    const user = await getUserInfo();
    await dispatch("setInfo", user);
  },
  // 获取角色列表
  async initRoles({ dispatch }) {
    const roles = await getRoles();
    await dispatch("setInfo", roles);
    await dispatch("setCurrentRole", roles[0] || "default");
  },

  async setInfo({ state, dispatch }, user) {
    state.info = user;
    await dispatch(
      "db/set",
      {
        dbName: "sys",
        path: "user.info",
        user: true,
        value: user
      },
      { root: true }
    );
    return user;
  },

  async setRole({ state, dispatch }, roles) {
    state.roles = roles;
    await dispatch(
      "db/set",
      {
        dbName: "sys",
        path: "user.roles",
        user: true,
        value: roles
      },
      { root: true }
    );
    return roles;
  },

  async setCurrentRole({ state, dispatch }, currentRole) {
    state.currentRole = currentRole;
    await dispatch(
      "db/set",
      {
        dbName: "sys",
        path: "user.currentRole",
        user: true,
        value: currentRole
      },
      { root: true }
    );
    return currentRole;
  },

  async load({ state, dispatch }) {
    const [info, roles, currentRole] = Promise.all([
      dispatch(
        "db/get",
        {
          dbName: "sys",
          path: "user.info",
          defaultValue: {},
          user: true
        },
        { root: true }
      ),
      dispatch(
        "db/get",
        {
          dbName: "sys",
          path: "user.roles",
          defaultValue: [],
          user: true
        },
        { root: true }
      ),
      dispatch(
        "db/get",
        {
          dbName: "sys",
          path: "user.currentRole",
          defaultValue: {},
          user: true
        },
        { root: true }
      )
    ]);
    state.info = info;
    state.roles = roles;
    state.currentRole = currentRole;
  },
  async init({ dispatch }) {
    // 加载用户信息
    dispatch("initUser");
    // 加载角色列表
    dispatch("initRoles");

    Promise.all([
      // 加载当前角色路由
      dispatch("router/init"),
      // 加载当前角色对应的权限列表
      dispatch("permission/init"),
      // 加载当前角色菜单
      dispatch("menu/init")
    ]);
  }
};

export default {
  namespaced: true,
  state,
  actions
};
